package net.apexes.commons.lang;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Path;

/**
 * @author <a href=mailto:hedyn@foxmail.com>HeDYn</a>
 */
public class DynamicClassLoader extends URLClassLoader {

    public DynamicClassLoader(ClassLoader classLoader) {
        super(new URL[0], classLoader);
    }

    public void addFile(Path file) {
        addFile(file.toFile());
    }

    public void addFile(File file) {
        if (file.exists()) {
            try {
                if (file.isDirectory()) {
                    File[] files = file.listFiles();
                    if (files != null) {
                        for (File f : files) {
                            if (f.exists() && f.isFile()) {
                                addURL(f.toURI().toURL());
                            }
                        }
                    }
                } else if (file.isFile()) {
                    addURL(file.toURI().toURL());
                }
            } catch (MalformedURLException ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    public void addClassPath(String classPath) {
        if (classPath == null || classPath.isEmpty()) {
            return;
        }
        String separator = System.getProperty("path.separator");
        String[] filenames = classPath.split(separator);
        for (String filename : filenames) {
            if (filename != null && !filename.isEmpty()) {
                addFile(new File(filename));
            }
        }
    }

    /**
     *
     * @param className
     * @return
     * @throws Exception
     */
    public Object newInstance(String className) throws Exception {
        Class<?> clazz = loadClass(className);
        return clazz.getConstructor().newInstance();
    }
}
